<template>
  <div class="upload flex-start">
    <div class="uploadImg" v-for="item in imgSrcList" :key="item.id">
      <img :src="item.src" alt="">
      <div class="delete flex-center" @click="deleteImg(item.id)">
        <i class="el-icon-close cp"></i>
      </div>
    </div>
    <div class="uploadBtn cp flex-center" v-if="showUploadBtn" @click="localUpload">
      <i class="el-icon-plus"></i>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      imgSrcList: [],
      showUploadBtn: true
    }
  },
  watch: {
    imgSrcList: {
      deep: true,
      handler (val) {
        this.showUploadBtn = val.length < 3
      }
    }
  },
  methods: {
    localUpload () {
      this.tools.createInputFile(null, 'image/x-png,image/gif,image/jpeg,image/bmp', true).then(res => {
        if (res.data.code === 200) {
          this.$emit('success', res.data.data)
          try {
            [...res.files].forEach((item, index) => {
              this.imgSrcList.push({ src: item, id: res.data.data[index].file_id })
              if (this.imgSrcList.length > 3) {
                throw new Error('只能添加三张截图')
              }
            })
          } catch (error) {
            this.$message({
              type: 'warning',
              message: String(error).split(':')[1],
              duration: 1000
            })
          }
        }
      })
    },
    deleteImg (id) {
      this.imgSrcList = this.imgSrcList.filter(item => item.id !== id)
      this.$emit('deleteImg', this.imgSrcList)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload {
  .uploadBtn {
    width: 124px;
    height: 124px;
    opacity: 1;
    border: 1px dashed #d8dee9;
    border-radius: 3px;
    i {
      color: #9eaac4;
      font-size: 20px;
    }
    &:hover {
      border-color: #304eec;
      i {
        color: #304eec;
      }
    }
  }
  .uploadImg{
    margin-right: 14px;
    position: relative;
    width: 124px;
    height: 124px;
    img{
      width: 100%;
      height: 100%;
    }
    .delete{
      border-radius: 50%;
      width: 16px;
      height: 16px;
      background: #ff3e6d;
      position: absolute;
      right: 0;
      top: 0;
      transform: translate(50%,-50%);
      i{
        font-size: 12px;
        color: #fff;
      }
    }
  }
}
</style>
